package com.example.yk

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.yk.entity.DetailEntityResult
import com.example.yk.entity.SubmitEntityResult
import com.example.zk3.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class DettailViewModel:BaseViewModel() {
    val success = MutableLiveData<DetailEntityResult>()
    val fail = MutableLiveData<String>()

    fun detail(id:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Int>()
                map.put("id",id)
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.detail(body)
                success.value = result
            }catch (e:Exception){
                fail.value = e.message
            }
        }
    }

    val submitSuccess = MutableLiveData<SubmitEntityResult>()
    val submitFail = MutableLiveData<String>()
    fun submit(id:Int){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Int>()
                map.put("goodsId",id)
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.submit(body)
                submitSuccess.value = result
            }catch (e:Exception){
                submitFail.value = e.message
            }
        }
    }
}